package cn.snailhd.server.user.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.snailhd.core.base.constant.MessageEnums;
import cn.snailhd.core.base.constant.ResponseConstant;
import cn.snailhd.core.base.dao.MyBatisDao;
import cn.snailhd.core.base.dao.RedisDao;
import cn.snailhd.core.base.domain.BaseResultDTO;
import cn.snailhd.core.base.domain.UserTokenDO;
import cn.snailhd.core.base.service.TokenService;
import cn.snailhd.server.config.ServerConfig;
import cn.snailhd.server.user.domain.LoginDTO;
import cn.snailhd.server.user.domain.UserDO;
import cn.snailhd.utils.AESUtil;
import cn.snailhd.utils.MD5;
import cn.snailhd.utils.RegexUtils;

@Service
public class UserService {
	
	@Autowired
	MyBatisDao dao;
	
	@Autowired
	RedisDao redis;
	
	@Autowired
	TokenService tokenService;
	
	
	/**
	 * 登陆
	 * @param loginDTO
	 * @param re
	 * @param httpSession
	 * @return
	 * @throws Exception
	 */
	public BaseResultDTO login(LoginDTO loginDTO,BaseResultDTO re) throws Exception{
		String loginName = loginDTO.getLoginName();
		UserDO user = null;
		if(loginName.matches(RegexUtils.REGEX_EMAIL)){ //登录名是邮箱
			user = queryUserByEmail(loginName);
		}
		else if(loginName.matches(RegexUtils.REGEX_MOBILE)){ //登录名是手机
			user = queryUserByTel(loginName);
		}
		if(null==user) 
			return re.setErrorCode(MessageEnums.LOGIN_USER_NOT_EXISTS);
		
		String password = loginDTO.getPassword();
		MD5 m = new MD5();
		if(!user.getPassword().equals(m.getMD5ofStr(password))){
			return re.setErrorCode(MessageEnums.LOGIN_USER_PWD_ERROR);
		}
		
		String token = tokenService.saveToken(user.getUserid());
		
		re.put("token", token);
		re.setSuccess();
		return re;
	}
	
	
	
	
	
		
	public UserDO queryUserByuserid(String userid){
		return dao.selectOne("user.queryUserByUserid", userid);
	}
	
	public UserDO queryUserByTel(String tel){
		return dao.selectOne("user.queryUserByTel", tel);
	}
	
	public UserDO queryUserByEmail(String email){
		return dao.selectOne("user.queryUserByEmail", email);
	}
	
	
	private String getToken(UserTokenDO tokenDO) throws Exception{
//		String text = JSON.toJSONString(tokenDO);
//		byte[] bs = AESUtil.encryDateAes(text, ServerConfig.AES_KEY);
//		return AESUtil.base64Encry(bs);
		return null;
	}
}
